// Copyright 2025 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'dart:convert';
import 'package:build/build.dart';
import 'package:crypto/crypto.dart';

class StylesHashBuilder implements Builder {
  const StylesHashBuilder();

  @override
  Map<String, List<String>> get buildExtensions => {
    'web/assets/css/main.css': ['lib/src/style_hash.dart'],
  };

  @override
  Future<void> build(BuildStep buildStep) async {
    final inputId = buildStep.inputId;
    final bytes = await buildStep.readAsBytes(inputId);
    final digest = sha256.convert(bytes);
    final hashString = base64.encode(digest.bytes).substring(0, 12);

    final outputContent =
        """
// Generated by docs_flutter_dev_site|stylesHashBuilder. Do not edit.
// dart format off

/// The generated hash of the `main.css` file.
const generatedStylesHash = '$hashString';
""";

    await buildStep.writeAsString(
      buildStep.allowedOutputs.single,
      outputContent,
    );
  }
}
